import React, { useEffect, useState } from 'react';
import { Modal, Form, Input, Select, DatePicker, Switch, message, Button, Space } from 'antd';
import { UploadOutlined } from '@ant-design/icons';
import dayjs from 'dayjs';
import { uploadAudio } from '@/services/systemManagementApi';

const { TextArea } = Input;
const { Option } = Select;

interface DailySentenceFormProps {
  visible: boolean;
  onCancel: () => void;
  onSubmit: (values: any) => void;
  initialValues?: LEARNING.DailySentenceModel;
  loading?: boolean;
}

const DailySentenceForm: React.FC<DailySentenceFormProps> = ({
  visible,
  onCancel,
  onSubmit,
  initialValues,
  loading = false,
}) => {
  const [form] = Form.useForm();
  const [audioUploading, setAudioUploading] = useState(false);

  // 处理初始值，将日期字符串转换为 Dayjs 对象
  useEffect(() => {
    if (visible && initialValues) {
      const formValues: any = { ...initialValues };

      // 如果有日期字段且是字符串，转换为 Dayjs 对象
      if (formValues.date && typeof formValues.date === 'string') {
        try {
          // 确保日期格式正确，并且是有效的日期
          const dateValue = dayjs(formValues.date);
          if (dateValue.isValid()) {
            formValues.date = dateValue;
          } else {
            console.warn('Invalid date format:', formValues.date);
            // 如果日期无效，设置为今天
            formValues.date = dayjs();
          }
        } catch (error) {
          console.error('Error parsing date:', formValues.date, error);
          // 如果解析出错，设置为今天
          formValues.date = dayjs();
        }
      } else if (!formValues.date) {
        // 如果没有日期，设置为今天
        formValues.date = dayjs();
      }

      form.setFieldsValue(formValues);
    } else if (visible && !initialValues) {
      // 新建时重置表单，设置默认日期为今天
      form.resetFields();
      form.setFieldsValue({
        date: dayjs(),
      });
    }
  }, [visible, initialValues, form]);

  // 处理音频上传
  const handleAudioUpload = async () => {
    const input = document.createElement('input');
    input.type = 'file';
    input.accept = 'audio/*';
    input.onchange = async (e) => {
      const file = (e.target as HTMLInputElement).files?.[0];
      if (!file) return;

      // 检查文件类型
      if (!file.type.startsWith('audio/')) {
        message.error('请选择音频文件');
        return;
      }

      // 检查文件大小 (限制为 50MB)
      if (file.size > 50 * 1024 * 1024) {
        message.error('音频文件大小不能超过 50MB');
        return;
      }

      setAudioUploading(true);
      try {
        const response = await uploadAudio(file);
        if (response.code === 200) {
          // 设置音频URL到表单
          form.setFieldsValue({
            audio_url: response.data.url
          });
          message.success('音频上传成功');
        } else {
          message.error(response.message || '音频上传失败');
        }
      } catch (error) {
        console.error('Audio upload error:', error);
        message.error('音频上传失败');
      } finally {
        setAudioUploading(false);
      }
    };
    input.click();
  };

  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();

      // 转换日期格式为 YYYY-MM-DD
      if (values.date && dayjs.isDayjs(values.date)) {
        values.date = values.date.format('YYYY-MM-DD');
      }

      onSubmit(values);
    } catch (error) {
      message.error('请检查表单输入');
    }
  };

  return (
    <Modal
      title={initialValues ? '编辑每日一句' : '新增每日一句'}
      open={visible}
      onCancel={onCancel}
      onOk={handleSubmit}
      confirmLoading={loading}
      width={600}
    >
      <Form
        form={form}
        layout="vertical"
      >
        <Form.Item
          name="date"
          label="日期"
          rules={[{ required: true, message: '请选择日期' }]}
        >
          <DatePicker
            style={{ width: '100%' }}
            placeholder="请选择日期"
            format="YYYY-MM-DD"
          />
        </Form.Item>

        <Form.Item
          name="chinese"
          label="句子内容"
          rules={[{ required: true, message: '请输入句子内容' }]}
        >
          <TextArea rows={3} placeholder="请输入句子内容" />
        </Form.Item>

        <Form.Item
          name="pinyin"
          label="拼音标注"
        >
          <TextArea rows={2} placeholder="请输入拼音标注" />
        </Form.Item>

        <Form.Item
          name="english"
          label="翻译"
        >
          <TextArea rows={2} placeholder="请输入翻译" />
        </Form.Item>

        <Form.Item
          name="source"
          label="来源"
        >
          <Input placeholder="请输入来源，如：《论语》" />
        </Form.Item>

        <Form.Item
          name="audio_url"
          label="音频地址"
          rules={[
            { type: 'url', message: '请输入有效的URL地址' }
          ]}
        >
          <Space.Compact style={{ width: '100%' }}>
            <Input
              placeholder="请输入音频地址或上传音频文件"
              style={{ flex: 1 }}
              value={form.getFieldValue('audio_url')}
            />
            <Button
              icon={<UploadOutlined />}
              loading={audioUploading}
              onClick={handleAudioUpload}
            >
              上传音频
            </Button>
          </Space.Compact>
        </Form.Item>

        <Form.Item
          name="tags"
          label="标签"
        >
          <Input placeholder="请输入标签，多个标签用逗号分隔" />
        </Form.Item>

        <Form.Item
          name="difficulty"
          label="难度等级"
          rules={[{ required: true, message: '请选择难度等级' }]}
        >
          <Select placeholder="请选择难度等级">
            <Option value="easy">简单</Option>
            <Option value="medium">中等</Option>
            <Option value="hard">困难</Option>
          </Select>
        </Form.Item>

        <Form.Item
          name="is_active"
          label="是否启用"
          valuePropName="checked"
          initialValue={true}
        >
          <Switch />
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default DailySentenceForm;
